#include		<stdio.h>
#include		<stdlib.h>
#include		<sys/types.h>
#include		<sys/stat.h>
#include		<fcntl.h>
#include		<string.h>
#include		<unistd.h>

#include		"list.h"
#include		"heap.h"
#include		"ftrace.h"

void			add_node_graph(s_func *func);

static void		pad(int depth)
{
  int i = 0;

  while (i < depth)
  {
    printf(" ");
    ++i;
  }
}

void			dsp_heap(s_heap *heap, int depth)
{
  s_list		*tmp;
  s_func		*func;
  s_func		*func_tmp;

  if (heap)
  {
    pad(depth);
    func = (s_func *) heap->value;
    printf("%lx %s\n", func->call_addr, func->name);
    add_node_graph(func);
    tmp = heap->childs;
    while (tmp)
    {
      func_tmp = (s_func *)((s_heap *)tmp->value)->value;
      add_node_link(func->id, func_tmp->id);
      dsp_heap((s_heap *) tmp->value, depth + 1);
      tmp = tmp->next;
    }
  }
}

void			destruct_heap(s_heap *heap,
    f_heap_destructor destructor, void *arg)
{
  s_list		*tmp;

  if (heap)
  {
    destructor(heap->value, arg);
    tmp = heap->childs;
    while (tmp)
    {
      destruct_heap((s_heap *) tmp->value, destructor, arg);
      tmp = tmp->next;
    }
    destruct_list(heap->childs);
    free(heap);
  }
}

s_heap			*heap_add(s_heap *parent, void *value)
{
  s_heap		*elem;

  elem = malloc(sizeof(*elem));
  if (!elem)
    return (NULL);
  elem->value = value;
  elem->childs = NULL;
  elem->parent = parent;
  if (!parent || list_add(&(parent->childs), (void *) elem))
    return (elem);
  return (NULL);
}
